<template>
	<view class="article-detail-container">
		<text class="title">{{articleDetail.title}}</text>
		<view class="meta">
			<text class="author">{{articleDetail.author}}</text>
			<text class="date">{{articleDetail.date}}</text>
		</view>
		<image class="cover" :src="articleDetail.image" mode="widthFix"></image>
		<rich-text class="content" :nodes="formatContent(articleDetail.content)"></rich-text>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getArticleDetail } from '@/api/article';
import { onLoad } from '@dcloudio/uni-app';

const articleDetail = ref({
	title: '',
	author: '',
	date: '',
	image: '',
	content: ''
});

// 格式化函数
const formatContent = (content) => {
  if (!content) return '';
  // 转换换行符
  return content
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\n/g, '<br>');
};

onLoad(async (options) => {
	const id = options.id;
	await fetchArticleDetail(id);
});

const fetchArticleDetail = async (id) => {
	uni.showLoading({
		title: '加载中...'
	});
	
	try {
		const response = await getArticleDetail({ id });
		if (response.code === "200") {
			articleDetail.value = {
				title: response.data.title,
				author: response.data.author || "岭南罗氏妇科",
				date: formatDate(response.data.createTime),
				image: response.data.coverImg ,
				content: response.data.content
			};
		}
	} catch (error) {
		console.error("获取文章详情失败:", error);
	} finally {
		uni.hideLoading({
		  success: (response) => {
		  },
		  complete: response => {
		  }
		});
	}
};

const formatDate = (dateStr) => {
	if (!dateStr) return "";
	const date = new Date(dateStr);
	return `${date.getFullYear()}年${String(date.getMonth() + 1).padStart(2, "0")}月${String(date.getDate()).padStart(2, "0")}日`;
};
</script>

<style lang="scss">
.article-detail-container {
	padding: 30rpx;
	background-color: #F8F5FF;
	.title {
		font-size: 36rpx;
		font-weight: bold;
		line-height: 1.4;
	}
	
	.meta {
		display: flex;
		justify-content: space-between;
		margin: 20rpx 0;
		font-size: 26rpx;
		color: #999;
	}
	
	.cover {
		width: 100%;
		border-radius: 12rpx;
		margin-bottom: 30rpx;
	}
	
	.content {
		font-size: 30rpx;
		line-height: 1.8;
	}
}
</style>